package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.UserLike;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.stream.Collectors;

@Service(version = "1.0.0")
public class UserLikeApiImpl implements UserLikeApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveUserLike(Long userId, Long likeUserId) {
        //先查询有没有喜欢
        Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        UserLike result = mongoTemplate.findOne(query, UserLike.class);
        if (result != null)
            return null;
        UserLike userLike = new UserLike();
        userLike.setUserId(userId);
        userLike.setLikeUserId(likeUserId);
        userLike.setId(ObjectId.get());
        userLike.setCreated(System.currentTimeMillis());
        mongoTemplate.save(userLike);
        return userLike.getId().toHexString();
    }

    //是否互相喜欢
    @Override
    public Boolean isMutualLike(Long userId, Long likeUserId) {
        Criteria criteria1 = Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId);
        Criteria criteria2 = Criteria.where("userId").is(likeUserId).and("likeUserId").is(userId);
        Query query = Query.query(new Criteria().orOperator(criteria1,criteria2));
        long count = mongoTemplate.count(query, UserLike.class);
        return count == 2;
    }

    @Override
    public Boolean deleteUserLike(Long userId, Long likeUserId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("likeUserId").is(likeUserId));
        return mongoTemplate.remove(query,UserLike.class).getDeletedCount() == 1;
    }

    @Override
    public Long queryEachLikeCount(Long userId) {
        List<UserLike> userLikeList = this.mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), UserLike.class);
        List<Long> likeUserIds = userLikeList.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());

        return this.mongoTemplate.count(Query.query(Criteria.where("userId").in(likeUserIds).and("likeUserId").is(userId)), UserLike.class);

    }


    @Override
    public Long queryLikeCount(Long userId) {
        return this.mongoTemplate.count(Query.query(Criteria.where("userId").is(userId)), UserLike.class);

    }


    @Override
    public Long queryFanCount(Long userId) {

        return this.mongoTemplate.count(Query.query(Criteria.where("likeUserId").is(userId)), UserLike.class);

    }

}